<?php
namespace System\Controller;

use Common\Controller\AdminbaseController;

class RbacController extends AdminbaseController {

    protected $role_model, $auth_access_model;

    public function _initialize() {
        parent::_initialize();
        $this->role_model = D("Common/SystemAdminRole");
    }

    // 角色管理列表
    public function index() {
        $data = $this->role_model->order(array("listorder" => "ASC", "id" => "DESC"))->select();
        $this->assign("roles", $data);
        $this->display();
    }

    // 添加角色
    public function roleadd() {
        $this->display();
    }

    // 添加角色提交
    public function roleadd_post() {
    	if (IS_POST) {
    		if ($this->role_model->create()!==false) {
    			if ($this->role_model->add()!==false) {
    				$this->success("添加角色成功",U("rbac/index"));
    			} else {
    				$this->error("添加失败！");
    			}
    		} else {
    			$this->error($this->role_model->getError());
    		}
    	}
    }

    // 删除角色
    public function roledelete() {
        $id = I("get.id",0,'intval');
        if ($id == 1) {
            $this->error("超级管理员角色不能被删除！");
        }
        $role_user_model=M("SystemAdminRoleUser");
        $count=$role_user_model->where(array('role_id'=>$id))->count();
        if($count>0){
        	$this->error("该角色已经有用户！");
        }else{
        	$status = $this->role_model->delete($id);
        	if ($status!==false) {
        		$this->success("删除成功！", U('Rbac/index'));
        	} else {
        		$this->error("删除失败！");
        	}
        }

    }

    // 编辑角色
    public function roleedit() {
        $id = I("get.id",0,'intval');
        if ($id == 1) {
            $this->error("超级管理员角色不能被修改！");
        }
        $data = $this->role_model->where(array("id" => $id))->find();
        if (!$data) {
        	$this->error("该角色不存在！");
        }
        $this->assign("data", $data);
        $this->display();
    }

    // 编辑角色提交
    public function roleedit_post() {
    	$id = I("request.id",0,'intval');
    	if ($id == 1) {
    		$this->error("超级管理员角色不能被修改！");
    	}
    	if (IS_POST) {
    		if ($this->role_model->create()!==false) {
    			if ($this->role_model->save()!==false) {
    				$this->success("修改成功！", U('Rbac/index'));
    			} else {
    				$this->error("修改失败！");
    			}
    		} else {
    			$this->error($this->role_model->getError());
    		}
    	}
    }

    // 角色授权
    public function authorize() {
        $this->auth_access_model = D("Common/SystemRbacAccess");
       //角色ID
        $roleid = I("get.id",0,'intval');
        if (empty($roleid)) {
        	$this->error("参数错误！");
        }
        import("Tree");
        $menu = new \Tree();
        $menu->icon = array('│ ', '├─ ', '└─ ');
        $menu->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = $this->initMenu();
        $newmenus=array();
        $priv_data=$this->auth_access_model->where(array("role_id"=>$roleid))->getField("rule_name",true);//获取权限表数据
//        重新添加新权限方法
		
		foreach ($result as $m){
        	$newmenus[$m['id']]=$m;
        }
		
        foreach ($result as $n => $t) {
        	$tid = $t['id'];
        	$power = M('system_power')->where("user_id = '$roleid' and find_in_set($tid,menu_id)")->find();
			if($power){
				$result[$n]['checked'] = 'checked';
			}else{
				$result[$n]['checked'] = '';
			}
        	$result[$n]['level'] = $this->_get_level($t['id'], $newmenus);
        	$result[$n]['style'] = empty($t['parentid']) ? '' : 'display:none;';
        	$result[$n]['parentid_node'] = ($t['parentid']) ? ' class="child-of-node-' . $t['parentid'] . '"' : '';
        }
        $str = "<tr id='node-\$id' \$parentid_node  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td>
    			</tr>";
        $menu->init($result);
        $categorys = $menu->get_tree(0, $str);
		$categorys.= $this->_authorize_cat($priv_data);
        $this->assign("categorys", $categorys);
        $this->assign("roleid", $roleid);
        $this->display();
    }

    // 角色授权提交
    public function authorize_post() {
    	$this->auth_access_model = D("Common/SystemRbacAccess");
    	if (IS_POST) {
//  		print_r($_POST);die;
    		$roleid = I("post.roleid",0,'intval');
    		if(!$roleid){
    			$this->error("需要授权的角色不存在！");
    		}
    		if (is_array($_POST['menuid']) && count($_POST['menuid'])>0) {
    			$del = M('system_power')->where("user_id = '$roleid'")->delete();
    			$data['user_id'] = $roleid;
				$data['menu_id'] = implode(',', $_POST['menuid']);
				$add = M('system_power')->add($data);
//				$menu_model=M("SystemMenu");
//				$auth_rule_model=M("SystemRbacRule");
//  			$del = M('system_rbac_access')->where(array("role_id"=>$roleid,'type'=>'admin_url'))->delete();
//  			foreach ($_POST['menuid'] as $menuid) {
//  				$menu=$menu_model->where(array("id"=>$menuid))->field("app,model,action")->find();
////					print_r($menu);
//  				if($menu){
//  					$app=$menu['app'];
//  					$model=$menu['model'];
//  					$action=$menu['action'];
//  					$name=strtolower("$app/$model/$action");
//						$auth_rule_model=M("SystemRbacRule");
//						if($model=='AdminInfor'){
//							$where['name']=array('like',"%publish/admininfor/%");
//						}elseif($model=='AdminInformation'){
//							$where['name']=array('like',"%publish/adminInformation/%");
//						}else{
//							$where['name']=array('like',"%$model%");
//						}
//						
//						$aa=$auth_rule_model->where($where)->select();
//  					for ($i=0;$i<count($aa);$i++){
//							$this->auth_access_model->add(array("role_id"=>$roleid,"rule_name"=>$aa[$i]['name'],'type'=>'admin_url'));
////						}
//  				}
//  			}

    			$this->success("授权成功！", U("Rbac/index"));
    		}else{
    			//当没有数据时，清除当前角色授权
    			$del = M('system_power')->where("user_id = '$roleid'")->delete();
//  			$this->auth_access_model->where(array("role_id" => $roleid))->delete();
    			$this->error("没有接收到数据，执行清除授权成功！");
    		}
    	}
    }

    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param int $roleid 需要检查的角色ID
     */
    private function _is_checked($menu, $roleid, $priv_data) {

    	$app=$menu['app'];
    	$model=$menu['model'];
    	$action=$menu['action'];
    	$name=strtolower("$app/$model/$action");
    	if($priv_data){
	    	if (in_array($name, $priv_data)) {
	    		return true;
	    	} else {
	    		return false;
	    	}
    	}else{
    		return false;
    	}

    }

    /**
     * 获取菜单深度
     * @param $id
     * @param $array
     * @param $i
     */
    protected function _get_level($id, $array = array(), $i = 0) {

        	if ($array[$id]['parentid']==0 || empty($array[$array[$id]['parentid']]) || $array[$id]['parentid']==$id){
        		return  $i;
        	}else{
        		$i++;
        		return $this->_get_level($array[$id]['parentid'],$array,$i);
        	}

    }

    //角色成员管理
    public function member(){
    	//TODO 添加角色成员管理

    }
	/**
	 * 角色授权-支持指定分类
	 * @Author    HTL
	 * @DateTime  2016-08-10T10:20:01+0800
	 * @param     string                   $priv_data[auth_access table data]
	 * @return    [type]                          [description]
	 */
	function _authorize_cat($priv_data)
	{
		$cat_id = intval(C("AUTHORIZE_CATID"));//from config.php ,该分类必须是一级分类
		if($cat_id<=0) return;
		
		$cats = M("SystemTerms")->where("status=1 and path like '%0-$cat_id%'")->order("parent,listorder,term_id")->getField("term_id as id,name,parent,path",true);
		if(!cats || count($cats)<=0) return;
		$cat_html     = "";//生成的html
		//根据不同level生成不同层级效果
		$level_spacer = array('','   ├─' ,'   │    ├─ ','   │    │    └─ ' );
		$str          = "<tr id='cat-#id#' #parentid_node#>
                           <td style='padding-left:30px;'>#spacer#<input type='checkbox' name='catid[]' value='#id#' level='#level#' #checked# onclick='javascript:checknode(this);'> #name#</td>
                        </tr>";
		foreach ($cats as $key => $value) {
			$checked       = in_array($value['id'],$priv_data)?"checked":"";  //权限中是否已经存在该分类id
			$level         = count(explode('-',$value['path']))-2;           //减2是因为:要去掉数据库中的0-不算和explode方法是从1开始的
			$parentid_node = ($value['parent']) ? ' class="child-of-cat-' . $value['parent'] . '"' : '';//父类
			$_str          = str_replace('#id#',$value['id'],$str);
			$_str          = str_replace("#spacer#",$level_spacer[$level],$_str);
			$_str          = str_replace("#level#",$level,$_str);
			$_str          = str_replace("#checked#",$checked,$_str);
			$_str          = str_replace("#parentid_node#",$parentid_node,$_str);
			$_str          = str_replace("#name#",$value['name'],$_str);
			$cat_html     .= $_str;
		}
		return '<tr><td><br></td></tr>'.$cat_html;
	}
	/**
	 * 将选择的分类保存到权限表中
	 * @Author    HTL
	 * @DateTime  2016-08-10T11:45:48+0800
	 * @param     [type]                   $catids [post catids]
	 * @param     [type]                   $roleid [current user roleid]
	 * @return    [type]                           [description]
	 */
	function _authorize_post_cat($catids,$roleid)
	{
		if(!$catids || count($catids)<=0 || $roleid<=0) return;
		//使用单独的type(cat_url)进行区分
		$this->auth_access_model->where(array("role_id"=>$roleid,'type'=>'cat_url'))->delete();
		foreach ($catids as $catid) {
			$this->auth_access_model->add(array("role_id"=>$roleid,"rule_name"=>$catid,'type'=>'cat_url'));
		}
	}

}

